<template>
  <div class="periodStatusMonitoring">
    <DFPageList ref="dfPageListRef" :page-options="pageOptions">
      <template #chart>
        <div class="page-chart">
          <div class="page-chart__head">
            <div class="head-left">
              {{ $t('periodStatusMonitoring.table.title') }}
            </div>
            <div class="head-right">
              <div class="bar-legend">
                <div class="legend legend--on">
                  <div class="marker"></div>
                  <div class="text">{{ $t('periodStatusMonitoring.table.online') }}</div>
                </div>
                <div class="legend">
                  <div class="marker"></div>
                  <div class="text">{{ $t('periodStatusMonitoring.table.offline') }}</div>
                </div>
              </div>
            </div>
          </div>
          <div class="page-chart__body">
            <div class="progress__box" v-for="item in pageData" :key="item.id">
              <div class="progress__left">
                <img v-if="item.img" class="img" :src="item.img" :alt="item.name" />
                <span v-else class="img-empty">{{ $t('common.tipMsg.imgNotUpload') }}</span>

                <div class="progress-info">
                  <span class="title">{{ item.name }}</span>
                  <span class="code">{{ item.code }}</span>
                </div>
              </div>
              <div class="progress__right">
                <ProgressBar :value="item.times" :today="isToday"></ProgressBar>
              </div>
            </div>
          </div>
        </div>
      </template>
    </DFPageList>
  </div>
</template>

<script setup lang="ts" name="PeriodStatusMonitoring">
  import ProgressBar from './ProgressBar.vue';

  import lang from './lang';

  import { useMixins } from '@/hooks/useMixins';

  import { listMachine } from '@/api/base/machine';

  import { parseTime, disablePreviousDate, getDateStr } from '@/utils/dateUtil';

  // import data from './data';
  import { machineStatusList } from '@render/api/reportForm/periodStatusMonitoring';

  import { storage } from '@/utils/Storage';

  const { loadLangFn } = useMixins();

  const dfPageListRef: any = ref(null);

  loadLangFn(lang);

  const machineList = ref([]);

  const date = ref({
    createEndTime: `${getDateStr(-1)} 23:59:59`,
    createStartTime: `${getDateStr(-1)} 00:00:00`,
    defaultValue: [
      new Date(`${getDateStr(-1)} 00:00:00`).getTime(),
      new Date(`${getDateStr(-1)} 23:59:59`).getTime(),
    ],
  });

  const setRequestDataFn = (e) => {
    const { entity } = e;
    entity.dateStartTime = date.value.createStartTime;
    entity.dateEndTime = date.value.createEndTime;
    delete entity.date;

    return {
      ...e,
      entity,
    };
  };

  const beforeResetFn = () => {
    date.value.createStartTime = `${getDateStr(-1)} 00:00:00`;
    date.value.createEndTime = `${getDateStr(-1)} 23:59:59`;
  };

  const pageOptions = {
    searchForm: {
      formSchemas: [
        {
          label: 'machineName',
          prop: 'machineCodeList',
          component: 'NSelect',
          options: machineList,
          componentProps: {
            multiple: true,
          },
        },
        {
          label: 'date',
          common: true,
          component: 'NDatePicker',
          defaultValue: new Date(getDateStr(-1)).getTime(),
          componentProps: {
            clearable: false,
            type: 'date',
            valueFormat: 'yyyy-MM-dd',
            format: 'yyyy-MM-dd',
            isDateDisabled: disablePreviousDate,
            defaultTime: ['00:00:00', '23:59:59'],
            onUpdateValue: (_, v: string[]) => {
              if (v) {
                date.value.createStartTime = v + ' 00:00:00';
                date.value.createEndTime = v + ' 23:59:59';
              } else {
                date.value.createStartTime = '';
                date.value.createEndTime = '';
              }
            },
          },
        },
      ],
      beforeResetFn,
      requestFn: async (row) => {
        const data = setRequestDataFn(row);

        const res = await machineStatusList(data);

        const { data: resData } = res;

        console.log(resData);

        pageData.value = parseDate(resData);
        isToday.value =
          parseTime(new Date(), '{y}-{m}-{d}') === date.value.createStartTime.split(' ')[0];

        return res;
      },
    },
    table: {
      noTable: true,
      afterSlotName: 'chart',
    },
  };

  const initDictData = async () => {
    const res = await Promise.all([listMachine()]);

    const [res2] = res;

    machineList.value =
      res2?.data.map((item) => ({ label: item.machineName, value: item.machineCode })) || [];

    nextTick(() => {
      dfPageListRef.value?.reloadTableFn();
    });
  };

  initDictData();

  function parseDate(dataList) {
    return dataList.map((item) => {
      const { machineCode, machineName, list, machinePicture } = item;

      return {
        id: machineCode,
        img: machinePicture ? `http://${storage.get('host')}:3000/file/${machinePicture}` : null,
        // ? baseURL + machine.fileUrl : "",
        name: machineName,
        code: machineCode,
        times: list
          .filter(({ machineStatus }) => machineStatus === 1)
          .sort((a, b) => a.startTime - b.startTime)
          .map((item) => {
            const { startTime, endTime: iEndTime } = item;

            const endTime = iEndTime ? iEndTime : new Date().getTime();

            item['endTime'] = endTime;

            const createStartTime = new Date(date.value.createStartTime).getTime();

            const createEndTime = new Date(date.value.createEndTime).getTime();

            return [
              parseTime(
                new Date(startTime <= createStartTime ? createStartTime : startTime),
                '{h}:{i}'
              ),
              parseTime(new Date(endTime <= createEndTime ? endTime : createEndTime), '{h}:{i}'),
            ];
          }),
      };
    });
  }

  const pageData = ref([]);

  const isToday = ref(false);
</script>

<style lang="less" scoped>
  .page-chart {
    width: 100%;
    margin-top: 16px;
    border-radius: 2px;
    padding: 24px;
    min-height: calc(100vh - 216px);
    background: #fff;
    &__head {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 24px;

      .head-left {
        font-size: 16px;
        font-weight: 500;
        color: #222;
      }
      .head-right {
        .bar-legend {
          display: flex;
          align-items: center;
          justify-content: center;

          .legend {
            display: flex;
            align-items: center;
            margin-left: 30px;
            &--on.legend {
              .marker {
                background-color: #52c570;
              }
            }
            .marker {
              width: 24px;
              height: 12px;
              margin-right: 8px;
              border-radius: 2px;
              background-color: #e1e1e1;
            }
            .text {
              font-size: 12px;
              color: #666;
            }
          }
        }
      }
    }
  }
  .progress {
    &__box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 24px;
      margin-bottom: 20px;
      background: #fafafa;
      border-radius: 8px;
    }
    &__left {
      position: relative;
      width: 280px;
      height: 160px;
      text-align: center;
      background-color: #f3f3f3;
      overflow: hidden;
      .img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        &-empty {
          display: block;
          margin-top: 73px;
          font-size: 14px;
          color: #999999;
        }
      }
      .progress-info {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        color: #fff;
        padding: 6px 14px;
        text-align: center;
        background-color: rgb(0 0 0 / 50%);
        .title {
          display: block;
          font-size: 14px;
          font-weight: 500;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .code {
          display: block;
          margin-top: 1px;
          font-size: 12px;
          font-weight: 500;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
    &__right {
      flex: 1 auto;
      padding: 0 24px 0 40px;
    }
  }
</style>
